package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")  //每分钟触发一次
    public void orderCs(){
        log.info("处理超时订单：{}", LocalDateTime.now());

        List<Orders> orderList = ordersMapper.listScOrder(Orders.PENDING_PAYMENT,LocalDateTime.now().plusMinutes(-15));
        if(orderList.size() > 0 && orderList!= null){
            for (Orders orders : orderList) {
                Orders o = Orders.builder()
                        .id(orders.getId())
                        .status(Orders.CANCELLED)
                        .cancelReason("订单超时未支付，系统自动取消订单")
                        .cancelTime(LocalDateTime.now())
                        .build();
                ordersMapper.update(o);
            }
        }
    }

    /**
     * 处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")  //每天凌晨1点触发一次
    public void ordersPs() {
        log.info("处理派送中订单：{}", LocalDateTime.now());
        List<Orders> orderList = ordersMapper.listScOrder(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if (orderList.size() > 0 && orderList != null) {
            for (Orders orders : orderList) {
                Orders o = Orders.builder()
                        .id(orders.getId())
                        .status(Orders.COMPLETED)
                        .build();
                ordersMapper.update(o);
            }
        }
    }
}
